<?php
/**
 * 参数验证基类
 */
namespace Raymond\BaseLib\ParamsValidate;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;

class ParamsValidate {

	/**
	 * 验证场景定义
	 * @var array
	 */
	protected $scene = [];

	/**
	 * 场景需要验证的规则
	 * @var array
	 */
	protected $only = [];

	public function __construct(){

	}

	/**
	 * 参数验证
	 * @param  [type] $rule    验证规则
	 * @param  [type] $message 错误信息
	 * @param  [type] $sceneArr 场景数组
	 * @param  [type] $scene 场景
	 * @return [type]          [description]
	 */
	public function goCheck($rule,$message,$sceneArr,$scene) {
		$data=Request::all();

		//读取验证规则
		$rules = $rule;
		//读取场景
		$this->scene=$sceneArr;

		//读取场景
		if (!$this->getScene($scene)) {
			return false;
		}

		//如果场景需要验证的规则不为空
		if (!empty($this->only)) {
			$new_rules = [];
			foreach ($this->only as $key => $value) {
				if (array_key_exists($value, $rules)) {
					$new_rules[$value] = $rules[$value];
				}
			}
			$rules = $new_rules;
		}

		$validator=Validator::make($data,$rules,$message);
		if($validator->fails()){
			return [
				'state'=>'err',
				'info'=>$validator->errors()->first()
			];
		}else{
			return ['state'=>'ok','info'=>''];  
		}
	}


	/**
	 * 获取数据验证的场景
	 * @access protected
	 * @param string $scene 验证场景
	 * @return void
	 */
	protected function getScene($scene = '') {
		$this->only = [];

		if (empty($scene)) {
			return true;
		}
		if (!isset($this->scene[$scene])) {
			//指定场景未找到写入error
			return [
				'state'=>'err',
				'info'=>'指定场景未找到'
			];
		}
		// 如果设置了验证适用场景
		$scene = $this->scene[$scene];
		if (is_string($scene)) {
			$scene = explode(',', $scene);
		}
		//将场景需要验证的字段填充入only
		$this->only = $scene;
		return true;
	}



}